<script setup>
import { ref, nextTick, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { login } from '../services/auth';

const router = useRouter();
const username = ref('');
const password = ref('');
const error = ref('');
const isLoading = ref(false);

// 计算属性 - 表单验证状态
const isFormValid = computed(() => {
  return username.value.trim().length > 0 && password.value.length > 0;
});

// 计算属性 - 用户名长度提示
const usernameLength = computed(() => {
  return username.value.length;
});

// 侦听器 - 监听用户名输入，清除错误消息
watch(username, () => {
  if (error.value) {
    error.value = '';
  }
  // 可以在这里添加更多的用户名实时验证逻辑
  console.log('用户名输入变化:', username.value);
});

// 侦听器 - 监听密码输入，记录输入强度（简单示例）
watch(password, (newValue) => {
  if (error.value) {
    error.value = '';
  }
  // 简单的密码强度检测
  if (newValue.length > 0) {
    const strength = newValue.length >= 8 ? '强' : newValue.length >= 6 ? '中' : '弱';
    console.log('密码强度:', strength);
  }
});

const handleLogin = async () => {
  error.value = '';
  
  // 基本验证
  if (!username.value || !password.value) {
    error.value = '请输入用户名和密码';
    return;
  }
  
  isLoading.value = true;
  
  try {
    const success = await login(username.value, password.value);
    if (success) {
      // 登录成功，先跳转到首页，避免直接加载复杂的个人中心页面造成卡顿
      // 同时使用nextTick确保状态更新完成
      await nextTick();
      router.push('/');
      // 提示用户登录成功
      alert('登录成功，欢迎回来！');
    } else {
      error.value = '用户名或密码错误';
    }
  } catch (err) {
    error.value = '登录失败，请稍后重试';
    console.error('Login error:', err);
  } finally {
    isLoading.value = false;
  }
};

const goToRegister = () => {
  router.push('/register');
};
</script>

<template>
  <div class="login-container">
    <div class="login-form">
      <h2 class="login-title">登录</h2>
      
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
      
      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名 <span class="input-hint">({{ usernameLength }}/20)</span></label>
          <input
            id="username"
            v-model="username"
            type="text"
            placeholder="请输入用户名"
            required
          />
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="password"
            type="password"
            placeholder="请输入密码"
            required
          />
        </div>
        
        <button 
          type="submit" 
          class="login-button"
          :disabled="isLoading || !isFormValid"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <!-- 注册链接 -->
      <div class="register-link">
        还没有账号？<button @click="goToRegister" class="link-button">立即注册</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 120px);
  padding: 40px 20px;
  background-color: var(--background-color);
}

.login-form {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: var(--shadow-md);
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  text-align: center;
  margin-bottom: 30px;
}

.error-message {
  background-color: #fee;
  color: #c33;
  padding: 12px;
  border-radius: var(--border-radius);
  margin-bottom: 20px;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 16px;
  transition: border-color 0.3s ease;
  background-color: var(--white);
}

.form-group input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(251, 114, 153, 0.1);
}

.login-button {
  width: 100%;
  padding: 14px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-top: 10px;
}

.login-button:hover:not(:disabled) {
  background-color: #e86387;
}

.login-button:disabled {
  background-color: var(--text-light);
  cursor: not-allowed;
}

.register-link {
  text-align: center;
  margin-top: 24px;
  font-size: 14px;
  color: var(--text-secondary);
}

.link-button {
  background: none;
  border: none;
  color: var(--primary-color);
  font-weight: 500;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  margin-left: 4px;
}

.link-button:hover {
  text-decoration: underline;
}

.input-hint {
  font-size: 12px;
  color: var(--text-light);
  font-weight: normal;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 20px;
  }
  
  .login-form {
    padding: 30px 24px;
  }
  
  .login-title {
    font-size: 24px;
    margin-bottom: 24px;
  }
}

@media (max-width: 480px) {
  .login-form {
    padding: 24px 20px;
  }
  
  .form-group input {
    padding: 10px;
    font-size: 15px;
  }
  
  .login-button {
    padding: 12px;
    font-size: 15px;
  }
}
</style>